package fb.vis.login;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class LoginManager
 */
@WebServlet(name = "LoginManager", urlPatterns = {"/LoginManager", "/Login"})
public class LoginManager extends HttpServlet {
    private static final long serialVersionUID = 1L;
    public static final String appId = "176786479143191";
    public static final String appSecret = "7e1317c364e6b90a00b4f93919851483";
    
    //A comma separated list of Permissions to request from the person using your app.
    public static final String PERMISSIONS = "friends_birthday,read_friendlists";

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     * response)
     */
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        response.setContentType("text/html;charset=UTF-8");
        doFacebookRedirect(request, response);
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     * response)
     */
    @Override
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        if (request.getCharacterEncoding() == null) {
            request.setCharacterEncoding("UTF-8");
        }
        response.setContentType("text/html;charset=UTF-8");
        doFacebookRedirect(request, response);

    }

    private void doFacebookRedirect(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        System.out.println(request.getServerName());
        System.out.println(request.getServerPort());
        System.out.println(request.getScheme());
        System.out.println(request.getServletContext().toString());
        System.out.println(request.getServletPath());
        String url = "https://www.facebook.com/dialog/oauth?client_id=" + appId
                + "&redirect_uri=http://localhost:8080/FBVis/AfterLogin&state="
                + session.getId() + "&scope="+PERMISSIONS;
        response.sendRedirect(url);
    }
}
